/**
 * Copyright (c) 2013 An Yaming,  All Rights Reserved
 */
package so.shanku.essential.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.*;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.alipay.android.msp.demo.UsedMobileSecurePayHelper;
import com.alipay.android.msp.demo.UsedMobileSecurePayHelper.IPayCallBack;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonMapOrListJsonMap2JsonUtil;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.LogUtil;
import so.shanku.essential.utils.WeixiPay;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tanghuan
 * @ClassName: CommitOrderActivity
 * @Description: 提交订单并支付
 * @date 2014年12月3日 下午7:53:40
 */
public class CommitOrderActivity extends BaseActivity {
	public final String TAG = this.getClass().getSimpleName();
	/**
	 * 使用支付宝 帮助类
	 */
	private UsedMobileSecurePayHelper helper;

	/**
	 * 选中的支付方式
	 */
	private int selectid = 0;
	private int payId = 1;

	private String orderMap;
	private JsonMap<String, Object> orderdata;

	/**
	 * 订单信息
	 */
	private String orderNum, productName, totalPrice;

	/**
	 * 微信数据
	 */
	private PayReq req;
	private final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
	private String prepayId;

	public static final int PLUGIN_VALID = 0;
	public static final int PLUGIN_NOT_INSTALLED = -1;
	public static final int PLUGIN_NEED_UPGRADE = 2;

	/**
	 * **************************************************************
	 * mMode参数解释： "00" - 启动银联正式环境 "01" - 连接银联测试环境
	 * ***************************************************************
	 */
	private String mMode = "00";
	// private String mMode = "01";
	private int retryNum = 0;
	// private static final String TN_URL_01 =
	// "http://202.101.25.178:8080/gateway/merchant/trade";

	/**
	 * @Fields tn : TODO(订单流水号)
	 */
	private String tn;
	private boolean isInstallUnionPayPlugin = false;

	@SuppressLint("NewApi")
	public void doStartUnionPayPlugin(Activity activity, String tn, String mode) {
		int ret = UPPayAssistEx.startPay(this, null, null, tn, mode);
		// UPPayAssistEx.s
		if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
			// 需要重新安装控件
			Log.e(TAG, " plugin not found or need upgrade!!!");

			Builder builder = new Builder(this,
					R.style.lightdialog2);
			builder.setTitle("提示");
			builder.setMessage("完成购买需要安装银联支付控件，是否安装？");

			builder.setNegativeButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							isInstallUnionPayPlugin = true;
							dialog.dismiss();

							payfailure();
						}
					});

			builder.setPositiveButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							//finish();
							payfailure();
						}
					});
			builder.create().show();
		}

	}

	@Override
	protected void onStart() {
		LogUtil.d(TAG,"onStart");
		//toast.showToast("onStart");
		super.onStart();
	}

	@Override
	protected void onRestart() {
		LogUtil.d(TAG,"onRestart");
		//toast.showToast("onRestart");
		super.onRestart();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.commit_order_layout);
		//setContentView(R.layout.activity_shopping_zhifu_peisong_way);
		// setCenter_title(R.string.shopping_zhifu_peisong_way_text_title);
		helper = new UsedMobileSecurePayHelper(this);
		msgApi.registerApp(MyApplication.WEIXIN_APP_ID);
		req = new PayReq();

		orderMap = getIntent().getStringExtra(ExtraKeys.Key_Msg2);
		orderdata = JsonParseHelper.getJsonMap(orderMap);

		orderNum = orderdata.getStringNoNull("orderNum");
		productName = orderdata.getStringNoNull("productName");
		totalPrice = orderdata.getStringNoNull("actualPayPrice");
		payId = orderdata.getInt("payId", 1);

		LogUtil.d(TAG, orderMap);
		//totalPrice = 0.01 + "";

		gopaytype();
	}



	/**
	 * 选择支付方式
	 */
	private void gopaytype() {
		// TODO Auto-generated method stub
		switch (payId) {
			case Constant.ALIPAY_PAYID:
				goApliay(orderNum, productName, totalPrice);
				break;
			case Constant.UNION_PAYID:
				goUnionpay(orderNum, productName, totalPrice);
				break;
			case Constant.WEICHAT_PAYID:
				goWeChatpay(orderNum, productName, totalPrice);
				break;

			default:
				break;
		}
	}

	/**
	 * 支付宝支付
	 *
	 * @param orderNum2
	 * @param productName2
	 * @param totalPrice2
	 */
	public void goApliay(String orderNum2, String productName2,
	                     String totalPrice2) {
		double price = Double.parseDouble(totalPrice2);
		helper.play(orderNum2, productName2, price, callBack);
	}

	/**
	 * 银联支付
	 *
	 * @param orderNum2
	 * @param productName2
	 * @param totalPrice2
	 */
	public void goUnionpay(String orderNum2, String productName2,
	                       String totalPrice2) {
		// TODO Auto-generated method stub
		// mLoadingDialog = ProgressDialog.show(mContext, // context
		// "", // title
		// R.string.loading+"", // message
		// true); // 进度是否是不确定的，这只和创建进度条有关
		/*************************************************
		 *
		 * 步骤1：从网络开始,获取交易流水号即TN
		 *
		 ************************************************/

		getData_GetYinLianOrderTradeNum();
	}

	/**
	 * 微信支付
	 *
	 * @param orderNum2
	 * @param productName2
	 * @param totalPrice2
	 */
	public void goWeChatpay(String orderNum2, String productName2,
	                        String totalPrice2) {
		IntentFilter myIntentFilter = new IntentFilter();
		// 服务初始化失败
		myIntentFilter.addAction(Constant.ACT_WEIXINPAYCODE);
		myIntentFilter.addAction(Constant.ACT_WEIXINLAUNCHER);
		registerReceiver(mpayBroadcastReceiver, myIntentFilter);
//		WeixiPay weixinpay = new WeixiPay();
		getData_GetWeChatPrepayId();

	}

	/**
	 * 获取微信prepayId
	 */
	private void getData_GetWeChatPrepayId() {

		Map<String, Object> params = new HashMap<String, Object>();

		params.put("OrderNum", orderNum);
		params.put("Amount", totalPrice);
		params.put("CreateIp", MyApplication.getInstance().getIP());
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.GetAction_GetWeiXinPrePayNum);
		queue.setParamsNoJson(params);
		queue.setWhat(what_GetWeiXinPrePayNum);
		queue.setCallBack(callBack2);
		getDataUtil.getData(queue);

	}

	/**
	 * 获取银联流水号
	 */
	private void getData_GetYinLianOrderTradeNum() {

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("OrderNum", orderNum);
		params.put("Amount", totalPrice);
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.GetAction_GetYinLianOrderPrePayNum);
		queue.setParamsNoJson(params);
		queue.setWhat(what_GetYinLianOrderPrePayNum);
		queue.setCallBack(callBack2);
		getDataUtil.getData(queue);

	}

	private final int what_GetYinLianOrderPrePayNum = 100;
	private final int what_GetWeiXinPrePayNum = 101;
	/**
	 * 加载数据结束时的回调
	 */
	private IGetServicesDataCallBack callBack2 = new IGetServicesDataCallBack() {

		@Override
		public void onLoaded(GetDataQueue entity) {
			LogUtil.d(TAG, entity.getInfo() + "  " + entity.toString());
			if (entity.isOk()) {
				if (ShowGetDataError.isOK(mContext,
						entity.getInfo())) {
					// if (what_crashpay == entity.what) {
					// toast.showToast(JsonParseHelper.getAttribute(
					// entity.getInfo(),
					// new String[] { JsonKeys.Key_Msg }));
					// goOrderDetail();
//					paysuccess();
					// } else
					if (what_GetYinLianOrderPrePayNum == entity.what) {
						List<JsonMap<String, Object>> data = JsonParseHelper
								.getJsonMap_List_JsonMap(entity.getInfo(),
										JsonKeys.Key_Info);
						if (data != null & data.size() > 0) {
							tn = data.get(0).getStringNoNull("YinLianPrePayOrderNum");
							startYinLanPlugin();
						}
					} else if (what_GetWeiXinPrePayNum == entity.what) {
						List<JsonMap<String, Object>> data = JsonParseHelper
								.getJsonMap_List_JsonMap(entity.getInfo(),
										JsonKeys.Key_Info);
						if (data != null & data.size() > 0) {
							prepayId = data.get(0).getStringNoNull(
									"WeiXinPrePayOrderNum");
							req = WeixiPay.genPayReq(req, prepayId);
							sendPayReq();
						}
					}
				} else {//getData_GetWeChatPrepayId();
//					if (retryNum < 2) {
//						if (what_GetWeiXinPrePayNum == entity.what) {
//							getData_GetWeChatPrepayId();
//						} else if (what_GetYinLianOrderPrePayNum == entity.what) {
//							getData_GetYinLianOrderTradeNum();
//						}
//					} else {
					LogUtil.d(TAG, "callBack2 payfailure" );
					payfailure();
					//}
					//retryNum++;
				}

			} else {
				ShowGetDataError.showNetError(mContext);
				LogUtil.d(TAG, "callBack2 payfailure" );
				payfailure();
			}
			loadingToast.dismiss();
		}
	};

	private void startYinLanPlugin() {
		if (TextUtils.isEmpty(tn)) {
			toast.showToast("网络连接失败异常");
			payfailure();

		} else {
			Log.i(TAG, "tn" + tn);
			/*************************************************
			 *
			 * 步骤2：通过银联工具类启动支付插件
			 *
			 ************************************************/
			doStartUnionPayPlugin(this, tn, mMode);
		}
	}

	private void sendPayReq() {

		msgApi.registerApp(MyApplication.WEIXIN_APP_ID);
		msgApi.sendReq(req);
	}

	IPayCallBack callBack = new IPayCallBack() {

		@Override
		public void payed(boolean isOK) {
			LogUtil.d(TAG, "IPayCallBack " + isOK);
			if (isOK) {
				paysuccess();
				// goOrderDetail();
			} else {
				payfailure();
				// getMyApplication().getMain().getTabHost().setCurrentTab(0);
				// Intent intent = new
				// Intent(ShoppingZhifuPeisongWayActivity.this,
				// MainActivity.class);
				// startActivity(intent);
			}
		}
	};


	@SuppressLint("NewApi")
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
	                                final Intent data) {
		/*************************************************
		 *
		 * 步骤3：处理银联手机支付控件返回的支付结果
		 *
		 ************************************************/
		LogUtil.d(TAG, "union pay onActivityResult " + requestCode + "  " + resultCode);
		if (data == null) {
			LogUtil.d(TAG, "union pay data is null");
			payfailure();
			return;
		}
		Bundle bundle = data.getExtras();
		String str = data.getExtras().getString("pay_result");
		LogUtil.d(TAG, "union pay data is:" + bundle + "pay_result:" + str);
		if (str.equalsIgnoreCase("success")) {
			paysuccess();
		} else {
			payfailure();
			// getMyApplication().getMain().getTabHost().setCurrentTab(0);
			// Intent intent = new Intent(QuickPaymentActivity.this,
			// MainActivity.class);
			// startActivity(intent);
		}

//		String msg = "";
//		/*
//		 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
//		 */
//		String str = data.getExtras().getString("pay_result");
//		if (str.equalsIgnoreCase("success")) {
//			msg = "支付成功！";
//		} else if (str.equalsIgnoreCase("fail")) {
//			msg = "支付失败！";
//		} else if (str.equalsIgnoreCase("cancel")) {
//			msg = "用户取消了支付";
//		}
//
//		Builder builder = new Builder(this,
//				R.style.lightdialog2);
//		builder.setTitle("支付结果通知");
//		builder.setMessage(msg);
//		builder.setInverseBackgroundForced(true);
//		// builder.setCustomTitle();
//		builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				dialog.dismiss();
//				if (data.getExtras().getString("pay_result")
//						.equalsIgnoreCase("success")) {
//					paysuccess();
//				} else {
//					payfailure();
//					// getMyApplication().getMain().getTabHost().setCurrentTab(0);
//					// Intent intent = new Intent(QuickPaymentActivity.this,
//					// MainActivity.class);
//					// startActivity(intent);
//				}
//
//			}
//
//		});
//		builder.create().show();

	}

	/**
	 * 微信支付结果
	 */
	protected BroadcastReceiver mpayBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			LogUtil.d(TAG, "mpayBroadcastReceiver " +intent.getIntExtra("result",0));
			if (Constant.ACT_WEIXINPAYCODE.equalsIgnoreCase(action)) {
				int result = intent.getIntExtra("result", 0);
				if (result == 0) {
					paysuccess();
				} else {
					payfailure();
				}
			} else if (Constant.ACT_WEIXINLAUNCHER.equalsIgnoreCase(action)) {

			}
		}
	};

	/**
	 * 支付成功
	 */
	private void paysuccess() {
		sendPayResult();
		orderdata.put("resultCode", 0);
		JsonMapOrListJsonMap2JsonUtil<String, Object> util = new JsonMapOrListJsonMap2JsonUtil<String, Object>();
		Intent intent = new Intent(mContext, OrderResultActivity.class);
		intent.putExtra(ExtraKeys.Key_Msg1, util.map2Json(orderdata));
		setResult(RESULT_OK);
		jumpTo(intent, true);
	}

	/**
	 * 支付失败
	 */
	private void payfailure() {
		sendPayResult();
		orderdata.put("resultCode", 1);
		JsonMapOrListJsonMap2JsonUtil<String, Object> util = new JsonMapOrListJsonMap2JsonUtil<String, Object>();
		Intent intent = new Intent(this, OrderResultActivity.class);
		intent.putExtra(ExtraKeys.Key_Msg1, util.map2Json(orderdata));
		intent.putExtra(ExtraKeys.Key_Msg2, isInstallUnionPayPlugin);
		setResult(RESULT_OK);
		jumpTo(intent, true);


//		Builder builder = new Builder(this);
//		builder.setTitle("温馨提示");
//		builder.setMessage("是否更改支付方式？");
//		builder.setPositiveButton("取消",
//				new DialogInterface.OnClickListener() {
//					public void onClick(DialogInterface arg0, int arg1) {
//						orderdata.put("resultCode", 1);
//						JsonMapOrListJsonMap2JsonUtil<String, Object> util = new JsonMapOrListJsonMap2JsonUtil<String, Object>();
//						Intent intent = new Intent(
//								CommitOrderActivity.this,
//								OrderResultActivity.class);
//						intent.putExtra(ExtraKeys.Key_Msg1,
//								util.map2Json(orderdata));
//
//						startActivity(intent);
//						CommitOrderActivity.this.finish();
//					}
//				});
//		builder.setNegativeButton("确定",
//				new DialogInterface.OnClickListener() {
//
//					public void onClick(DialogInterface arg0, int arg1) {
//						//jumpTo(Pa);
//					}
//				});
//		builder.show();
	}

	private void sendPayResult() {
		sendBroadcast(new Intent(Constant.ACT_PAY_OVER));
	}


}
